package com.xoa.dev.efficiency.service.impl;

import com.xoa.dao.WFE.WFEFlowRunMapper;
import com.xoa.dao.WFE.WFEFlowRunPrcsMapper;
import com.xoa.dao.attend.AttendSetMapper;
import com.xoa.dao.attendance.UserDutyMapper;
import com.xoa.dao.department.DepartmentMapper;
import com.xoa.dao.users.UserExt2Mapper;
import com.xoa.dao.users.UsersMapper;
import com.xoa.dao.workflow.FlowPrivMapper;
import com.xoa.dao.workflow.FlowRunMapper;
import com.xoa.dao.workflow.FlowRunPrcsMapper;
import com.xoa.dao.workflow.FlowTypeModelMapper;
import com.xoa.dev.efficiency.dao.FlowAbilityMonitorMapper;
import com.xoa.dev.efficiency.dao.FlowParaMapper;
import com.xoa.dev.efficiency.dao.FlowSettingHolidayMapper;
import com.xoa.dev.efficiency.model.FlowAbilityMonitor;
import com.xoa.dev.efficiency.model.FlowPara;
import com.xoa.dev.efficiency.model.FlowSettingHoliday;
import com.xoa.dev.efficiency.model.Middle;
import com.xoa.dev.efficiency.service.FlowRunFuService;
import com.xoa.model.attend.AttendSet;
import com.xoa.model.attendance.UserDuty;
import com.xoa.model.department.Department;
import com.xoa.model.users.Users;
import com.xoa.model.workflow.FlowRun;
import com.xoa.model.workflow.FlowRunPrcs;
import com.xoa.model.workflow.FlowTypeModel;
import com.xoa.util.*;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.log.FileUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.common.wrapper.BaseWrapper;
import com.xoa.util.common.wrapper.BaseWrappers;
import com.xoa.util.page.PageParams;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sound.midi.MidiDevice;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@EnableScheduling
public class FlowRunFuServiceImpl implements FlowRunFuService {

    @Autowired
    WFEFlowRunMapper wfeFlowRunMapper;
    @Autowired
    FlowPrivMapper flowPrivMapper;
    @Autowired
    FlowParaMapper flowParaMapper;
    @Autowired
    UsersMapper usersMapper;
    @Autowired
    private FlowAbilityMonitorMapper flowAbilityMonitorMapper;
    @Autowired
    private FlowRunMapper flowRunMapper;
    @Autowired
    private DepartmentMapper departmentMapper;
    @Autowired
    private FlowTypeModelMapper flowTypeModelMapper;
    @Autowired
    protected WFEFlowRunPrcsMapper wfeFlowRunPrcsMapper;
    @Autowired
    private FlowSettingHolidayMapper flowSettingHolidayMapper;
    @Autowired
    private AttendSetMapper attendSetMapper;
    @Autowired
    private UserExt2Mapper userExt2Mapper;
    @Autowired
    private UserDutyMapper userDutyMapper;
    @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;
    //设置前台得到值的名字
    String tiqianbanjie = "tiqianbanjie";
    String anshibanjie = "anshibanjie";
    String chaoshibanjie = "chaoshibanjie";
    String anshibanli = "anshibanli";
    String chaoshibanli = "chaoshibanli";
    @Resource
    private FlowRunPrcsMapper flowRunPrcsMapper;
    private static SimpleDateFormat sdf = new SimpleDateFormat(
            "yyyy-MM-dd HH:mm:ss");

    private static final Logger logger = LoggerFactory.getLogger(FlowRunFuServiceImpl.class);

    public BaseWrappers queryFlowRunZhong(Integer page, Integer pageSize, boolean useFlag, HttpServletResponse response, HttpServletRequest request, Integer runId, String runName, String state, String beginDate, String endDate, String status) {
        BaseWrappers baseWrapper = new BaseWrappers();
        /**
         * 查出重点工作流程号
         */
        Map<String, Object> map1 = new HashMap<>();
        PageParams pageParams = new PageParams();
        pageParams.setPage(page);
        pageParams.setPageSize(pageSize);
        pageParams.setUseFlag(useFlag);
        map1.put("page", pageParams);
        map1.put("paraName", "FLOW_ID_Q");
        List<FlowPara> flowParaList = flowParaMapper.selectFlowPara(map1);
        //得到重点工作确认流程号:126
        String flowId = flowParaList.get(0).getParaValue();
        /**
         * 查出流程号是126 的工作的流水号(String串）
         */
        List<FlowRun> flowRunList = wfeFlowRunMapper.selectZhongId(flowId);
        List<Integer> runIds = new ArrayList<>();
        for (FlowRun flowRun : flowRunList) {
            runIds.add(flowRun.getRunId());
        }
        map1.put("allRunIds", runIds);
        map1.put("runIdsss", runId);
        map1.put("workTitle", runName);
        map1.put("fanwei", state);
        map1.put("beginTime", beginDate);
        map1.put("endTime", endDate);
        map1.put("zhuangtai", status);
        /**
         * 查出重点工作确认列表
         */
        List<FlowAbilityMonitor> flowRunModelPrcsList = flowAbilityMonitorMapper.selectZhongList(map1);

        for (FlowAbilityMonitor flowAbilityMonitor : flowRunModelPrcsList) {
            //            根据流水号查找流程信息
            FlowRun flowRun = wfeFlowRunMapper.selectBuRunId(flowAbilityMonitor.getRunId());
            flowAbilityMonitor.setFlowRun(flowRun);

            if (flowAbilityMonitor.getWorkEnd() != null) {
                flowAbilityMonitor.setStatus("已结束");
            } else {
                flowAbilityMonitor.setStatus("执行中");
            }
            SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            flowAbilityMonitor.getWorkStart();

        }
        TimeFunc<FlowAbilityMonitor> timeFunc = new TimeFunc<FlowAbilityMonitor>();

        List<FlowAbilityMonitor> flowRunModelPrcsLists = timeFunc.format_time_diff(flowRunModelPrcsList, "workDeadline", "workStart", "workEnd");
        if (flowRunModelPrcsLists.size() > 0) {
            baseWrapper.setDatas(flowRunModelPrcsLists);
            baseWrapper.setTotal(pageParams.getTotal());
        }
        baseWrapper.setFlag(true);
        baseWrapper.setMsg("ok");
        return baseWrapper;
    }


    /**
     * 两个时间相差距离多少天多少小时多少分多少秒
     *
     * @param str1 时间参数 1 格式：1990-01-01 12:00:00
     * @param str2 时间参数 2 格式：2009-01-01 12:00:00
     * @return String 返回值为：xx天xx小时xx分xx秒
     */
    public String getDistanceTime(String str1, String str2, String uid) {
        SimpleDateFormat df = new SimpleDateFormat(
                "yyyy-MM-dd HH:mm:ss");
        Date one;
        Date two;
        long day = 0;
        long hour = 0;
        long min = 0;
        long sec = 0;
        try {
            one = df.parse(str1);
            two = df.parse(str2);
            //获取排班时间
            Users users = usersMapper.findUsersByuserId(uid);
            AttendSet attendSet = attendSetMapper.queryAttendSetuId(users.getUid());
            List<Map<Object, Object>> list = new ArrayList<>();
            if (attendSet != null) {
                Map<Object, Object> map = new HashMap<>();
                if (!StringUtils.checkNull(attendSet.getAtime1()) && !StringUtils.checkNull(attendSet.getAtime2())) {
                    map.put(attendSet.getAtime1(), attendSet.getAtime2());
                }
                if (!StringUtils.checkNull(attendSet.getAtime3()) && !StringUtils.checkNull(attendSet.getAtime4())) {
                    map.put(attendSet.getAtime3(), attendSet.getAtime4());
                }
                if (!StringUtils.checkNull(attendSet.getAtime5()) && !StringUtils.checkNull(attendSet.getAtime6())) {
                    map.put(attendSet.getAtime5(), attendSet.getAtime6());
                }
                map.put("holiday", attendSet.getWorkdate());
                list.add(map);
            }
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String time3 = simpleDateFormat.format(one); //开始时间转为 年月日
            String time4 = simpleDateFormat.format(two);//办理时限转为 年月日
            //获取节假日
            List<FlowSettingHoliday> holidays = flowSettingHolidayMapper.selectAll(time4, time3);

            FlowRunFuServiceImpl.time(one, two, list, holidays);


            long time1 = one.getTime();
            long time2 = two.getTime();
            long diff;
            diff = time2 - time1;

            day = diff / (24 * 60 * 60 * 1000);
            hour = (diff / (60 * 60 * 1000) - day * 24);
            //min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60); 分钟
            sec = (diff / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //+ min + "分"
        return day + "天" + hour + "小时";
    }

    /**
     * 常规工作监察
     *
     * @param page
     * @param pageSize
     * @param useFlag
     * @param response
     * @param request
     * @param runId
     * @param runName
     * @param state
     * @param beginDate
     * @param endDate
     * @param userId
     * @return
     */
    public BaseWrappers queryFlowRunChang(Integer page, Integer pageSize, boolean useFlag,
                                          HttpServletResponse response, HttpServletRequest request,
                                          Integer runId, String runName, String state,
                                          String beginDate, String endDate, String userId, String status) {
        BaseWrappers baseWrapper = new BaseWrappers();
        //先查询当前人员的权限
        try {
            Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
            Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
            List<FlowPara> flowParaList = flowParaMapper.getFlowParaList();
            Map<String, Object> map1 = new HashMap<>();
            //分页
            if (useFlag == true) {
                Integer startPage = (page - 1) * pageSize;
                map1.put("startPage", startPage);
                map1.put("endPage", pageSize);
            }
            if (state != null) {
                if (state.equals("6")) {
                    String[] userIds = userId.split(",");
                    map1.put("userId", userIds);
                } else if (state.equals("2")) {
                    map1.put("userId", user.getUserId());
                } else if (state.equals("")) {
                    state = null;
                }
            }
            map1.put("status", status);
            map1.put("state", state);
            map1.put("runId", runId);
            map1.put("runName", runName);
            map1.put("beginDate", beginDate);
            map1.put("endDate", endDate);

            Map<String, String> flowParaMap = new HashMap();
            for (int i = 0; i < flowParaList.size(); i++) {
                FlowPara flowPara = flowParaList.get(i);
                flowParaMap.put(flowPara.getParaName(), flowPara.getParaValue());
            }
            Integer userPrar = this.get_user_right(user, flowParaMap);
            //查看是否有监察权限
            if (userPrar != 0) {
                //用户可查看的用户串
                String userIdreq = "";
                //最终查询List
                List<String> userIdList = new ArrayList<>();
                if (userPrar == 3) {
                    userIdreq = isPara(userPrar, user);
                    if (state != null && userId != null && !userId.equals("")) {
                        String[] userArrays = userId.split(",");
                        for (String userArray : userArrays) {
                            if (userIdreq.contains(userArray + ",")) {
                                userIdList.add(userArray);
                            }
                        }
                    } else {
                        if (userIdreq != null && !userIdreq.equals("")) {
                            String[] userIdArray = userIdreq.split(",");
                            userIdList = new ArrayList<>(Arrays.asList(userIdArray));
                        }

                    }
                } else if (userPrar == 2) {
                    userIdreq = isPara(userPrar, user);
                    if (state != null && userId != null && !userId.equals("")) {
                        String[] userArrays = userId.split(",");
                        for (String userArray : userArrays) {
                            if (userIdreq.contains(userArray + ",")) {
                                userIdList.add(userArray);
                            }
                        }
                    } else {
                        if (userIdreq != null && !userIdreq.equals("")) {
                            String[] userIdArray = userIdreq.split(",");
                            userIdList = new ArrayList<>(Arrays.asList(userIdArray));
                        }
                    }
                } else if (userPrar == 1) {
                    if (state != null && userId != null && !userId.equals("")) {
                        String[] userArrays = userId.split(",");
                        for (String userArray : userArrays) {
                            userIdList.add(userArray);
                        }
                    } else {
                        map1.put("para", userPrar);
                    }
                }
                if (userIdList != null && userIdList.size() > 0) {
                    map1.put("userIdList", userIdList);
                }
                //取出受监察的常规工作id
                String flowSelectId = flowParaMap.get("FLOW_SELECT_ID");
                if (flowSelectId != null && !flowSelectId.equals("")) {
                    String[] flowIds = flowSelectId.split(",");
                    map1.put("flowIds", flowIds);
                    Integer totalCount = flowAbilityMonitorMapper.getRunIdsCountByFlowIds(map1);
                    List<Integer> idList = flowAbilityMonitorMapper.getRunIdsByFlowIds(map1);
                    map1.put("idList", idList);
                    map1.put("flowIds", flowIds);
                    if (idList != null) {
                        List<Middle> middleList = flowAbilityMonitorMapper.getChangGuiList(map1);
                        if (middleList != null && middleList.size() > 0) {
                            for (Middle middle : middleList) {
                                middle = setTimeOut(middle);
                            }
                        }
                        if (middleList != null && middleList.size() > 0) {
                            baseWrapper.setDatas(middleList);
                            baseWrapper.setTotal(totalCount);
                            baseWrapper.setMsg("ok");
                            baseWrapper.setObject(userPrar);
                        }
                    }
                } else {
                    baseWrapper.setFlag(false);
                    baseWrapper.setMsg("未查询到需要监察的工作");
                }
            } else {
                baseWrapper.setFlag(false);
                baseWrapper.setMsg("您没有权限");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //getChangGuiWork(request,runName,status,"","",beginDate,endDate,"");
        baseWrapper.setFlag(true);
        return baseWrapper;
    }

    //装配时限属性
    public Middle setTimeOut(Middle middle) {
        if (middle != null) {
            String timeOut = middle.getTimeOut();
            if (timeOut != null && !timeOut.equals("")) {
                //获取时限，小时单位hour
                if (timeOut.contains(",")) {
                    timeOut = timeOut.split(",")[0];
                }
                Integer outTime = null;
                try {
                    outTime = Integer.parseInt(timeOut);
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                    middle.setTimeOutStr("出现脏数据");
                    return middle;
                }
                Integer outTimeIn = outTime * 60 * 60;
                //获取创建时间
                String createTime = middle.getCreateTime();
                //将创建时间转换时间戳
                Integer createTimeInt = DateFormat.getTime(createTime);
                //需要在manageTime时间前办理完毕，办理时限
                Integer manageTime = createTimeInt + outTimeIn;
                //获取当前时间的时间戳
                Integer atPresentTime = Integer.parseInt(String.valueOf(new Date().getTime()).substring(0, 10));
                //据办理值
                Integer juBan = Math.abs(atPresentTime - manageTime);
                String juBanStr = DateFormat.returnTime(juBan);
                String timeOutStr = DateFormat.returnTime(outTimeIn);
                middle.setTimeOutStr(timeOutStr);
                //如果是未接受和办理中状态，有据办理和超时办理
                if (middle.getPrcsFlag() == 1 || middle.getPrcsFlag() == 2) {
                    //如果当前时间大于办理时限
                    if (atPresentTime > manageTime) {
                        middle.setJuTimeOutStr("超出" + juBanStr);
                        middle.setTimeStatus("已超时办理中");
                    }//否则如果小于办理时限
                    else if (atPresentTime < manageTime) {
                        middle.setJuTimeOutStr("剩余" + juBanStr);
                        middle.setTimeStatus("正常办理中");
                    }
                } else if (middle.getPrcsFlag() == 3 || middle.getPrcsFlag() == 4) {
                    //获取办结时间
                    String deliverTime = middle.getDeliverTime();
                    //办结时间时间戳
                    Integer deliverTimeInt = DateFormat.getTime(deliverTime);
                    Integer banjieTime = Math.abs(deliverTimeInt - manageTime);
                    String banjieTimeStr = DateFormat.returnTime(banjieTime);
                    if (deliverTimeInt > manageTime) {
                        middle.setJuTimeOutStr("超出" + banjieTimeStr);
                        middle.setTimeStatus("已超时办结");
                    } else if (deliverTimeInt < manageTime) {
                        middle.setJuTimeOutStr("剩余" + banjieTimeStr);
                        middle.setTimeStatus("已按时办结");
                    }

                }

            } else {
                if (middle.getPrcsFlag() == 1 || middle.getPrcsFlag() == 2) {
                    middle.setTimeStatus("正常办理中");
                } else if (middle.getPrcsFlag() == 3 || middle.getPrcsFlag() == 4) {
                    middle.setTimeStatus("已按时办结");
                }
                middle.setJuTimeOutStr("没有时限");
                middle.setTimeOutStr("没有时限");
            }
        }
        return middle;
    }

    /**
     * 重点统计
     *
     * @param request
     * @param response
     * @param page
     * @param pageSize
     * @param useFlag
     * @param userIds
     * @param deptIds
     * @param beginDate
     * @param endDate
     * @param export
     * @return
     */
    public BaseWrappers zhongTong(HttpServletRequest request, HttpServletResponse response, Integer page, Integer pageSize, Boolean useFlag, String userIds, String deptIds, String beginDate, String endDate, Integer export) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
        List<String> okParaList = new ArrayList<>();
        //查看权限
        List<FlowPara> flowParaList = flowParaMapper.getFlowParaList();
        Map<String, String> flowParaMap = new HashMap();
        for (int i = 0; i < flowParaList.size(); i++) {
            FlowPara flowPara = flowParaList.get(i);
            flowParaMap.put(flowPara.getParaName(), flowPara.getParaValue());
        }
        //权限级别
        Integer para = get_user_right(users, flowParaMap);
        BaseWrappers baseWrapper = new BaseWrappers();
        List<Map<String, Object>> mapList = new ArrayList<>();
        if (para != 0) {
            //前台传过来要查询的人员
            List<String> userIdList = new ArrayList<>();
            //从数据库查询出的受管辖人员字符串
            String userIdReq = "";
            if (deptIds != null && !deptIds.equals("")) {
                String[] deptIdArray = deptIds.split(",");
                //得到要查询的部门下人员
                List<Users> usersList = usersMapper.selectUserByDeptIds(deptIdArray);
                for (Users users1 : usersList) {
                    userIdList.add(users1.getUserId());
                }

            }
            if (userIds != null && !userIds.equals("")) {
                String[] userIdArray = userIds.split(",");
                for (String userId : userIdArray) {
                    userIdList.add(userId);
                }
            }
            if (para == 2) {
                //只能查看自己部门下的人员和自己负责的部门下的人员
                List<String> deptIdList =flowAbilityMonitorMapper.getDepartmentByManager(users.getUserId());
                deptIdList.add(users.getDeptId().toString());
                //快速去重
                Set set = new HashSet(deptIdList);
                deptIdList = new ArrayList<>(set);
                if (deptIdList != null && deptIdList.size() > 0) {
                    String[] deptIdArray = new String[deptIdList.size()];
                    deptIdArray = deptIdList.toArray(deptIdArray);
                    List<Users> usersPara = usersMapper.selectUserByDeptIds(deptIdArray);
                    for (Users users1 : usersPara) {
                        userIdReq += users1.getUserId() + ",";
                    }
                }
                for (String userId : userIdList) {
                    if (userIdReq.contains(userId + ",")) {
                        okParaList.add(userId);
                    }
                }
            } else if (para == 3) {
                //只能查看自己和自己部门下的
                List<Users> usersList = usersMapper.getUsersByDeptId(users.getDeptId());
                for (Users users1 : usersList) {
                    userIdReq += users1.getUserId() + ",";
                }
                for (String userId : userIdList) {
                    if (userIdReq.contains(userId + ",")) {
                        okParaList.add(userId);
                    }
                }
            } else {
                okParaList = userIdList;
            }

            Map<String, Object> map = new HashMap<>();
            map.put("tiqianbanjie", tiqianbanjie);
            map.put("anshibanjie", anshibanjie);
            map.put("chaoshibanjie", chaoshibanjie);
            map.put("anshibanli", anshibanli);
            map.put("chaoshibanli", chaoshibanli);
            map.put("beginDate", beginDate);
            map.put("endDate", endDate);
            for (String userId : okParaList) {
                map.put("userId", userId);
                Map<String, Object> tongJiMap = flowAbilityMonitorMapper.getZhongDianTongJi(map);
                Users user = usersMapper.getUsersByuserId(userId);
                String deptName = departmentMapper.getDeptNameById(user.getDeptId());
                tongJiMap.put("userName", user.getUserName());
                tongJiMap.put("deptName", deptName);
                mapList.add(tongJiMap);
            }
        } else {
            //没有权限
        }
        if(export==1||export==2){
            exportExcel(export,mapList,response);
        }
        if (mapList != null) {
            //baseWrapper.setTotal(flowAbilityMonitorList.size());
            baseWrapper.setMsg("ok");
            baseWrapper.setFlag(true);
            baseWrapper.setDatas(mapList);
        }
        return baseWrapper;
    }

    //返回有权限看的用户userId串
    public String isPara(Integer para, Users users) {
        String userIdReq = "";
        if (para == 2) {
            //只能查看自己部门下的人员和自己负责的部门下的人员
            List<String> deptIdList = flowAbilityMonitorMapper.getDepartmentByManager(users.getUserId());
            deptIdList.add(users.getDeptId().toString());
            //快速去重
            Set set = new HashSet(deptIdList);
            deptIdList = new ArrayList<>(set);
            if (deptIdList != null && deptIdList.size() > 0) {
                String[] deptIdArray = new String[deptIdList.size()];
                deptIdArray = deptIdList.toArray(deptIdArray);
                List<Users> usersPara = usersMapper.selectUserByDeptIds(deptIdArray);
                for (Users users1 : usersPara) {
                    userIdReq += users1.getUserId() + ",";
                }
            }
        } else if (para == 3) {
            //只能查看自己和自己部门下的
            List<Users> usersList = usersMapper.getUsersByDeptId(users.getDeptId());
            for (Users users1 : usersList) {
                userIdReq += users1.getUserId() + ",";
            }
        }
        return userIdReq;
    }

    /**
     * 常规工作统计
     *
     * @param request
     * @param response
     * @param page
     * @param pageSize
     * @param useFlag
     * @param userIds
     * @param deptIds
     * @param beginDate
     * @param endDate
     * @param export
     * @return
     */
    public BaseWrappers changTong(HttpServletRequest request, HttpServletResponse response,
                                  Integer page, Integer pageSize, Boolean useFlag,
                                  String userIds, String deptIds,
                                  String beginDate, String endDate, Integer export) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
        List<String> okParaList = new ArrayList<>();
        //查看权限
        List<FlowPara> flowParaList = flowParaMapper.getFlowParaList();
        Map<String, String> flowParaMap = new HashMap();
        for (int i = 0; i < flowParaList.size(); i++) {
            FlowPara flowPara = flowParaList.get(i);
            flowParaMap.put(flowPara.getParaName(), flowPara.getParaValue());
        }
        //权限级别
        Integer para = get_user_right(users, flowParaMap);
        BaseWrappers baseWrapper = new BaseWrappers();
        List<Map<String, Object>> mapList = new ArrayList<>();
        if (para != 0) {
            //前台传过来要查询的人员
            List<String> userIdList = new ArrayList<>();
            //从数据库查询出的受管辖人员字符串
            String userIdReq = "";
            if (deptIds != null && !deptIds.equals("")) {
                String[] deptIdArray = deptIds.split(",");
                //得到要查询的部门下人员
                List<Users> usersList = usersMapper.selectUserByDeptIds(deptIdArray);
                for (Users users1 : usersList) {
                    userIdList.add(users1.getUserId());
                }

            }
            if (userIds != null && !userIds.equals("")) {
                String[] userIdArray = userIds.split(",");
                for (String userId : userIdArray) {
                    userIdList.add(userId);
                }
            }
            if (para == 2) {
                //只能查看自己部门下的人员和自己负责的部门下的人员
                List<String> deptIdList = flowAbilityMonitorMapper.getDepartmentByManager(users.getUserId());
                deptIdList.add(users.getDeptId().toString());
                //快速去重
                Set set = new HashSet(deptIdList);
                deptIdList = new ArrayList<>(set);
                if (deptIdList != null && deptIdList.size() > 0) {
                    String[] deptIdArray = new String[deptIdList.size()];
                    deptIdArray = deptIdList.toArray(deptIdArray);
                    List<Users> usersPara = usersMapper.selectUserByDeptIds(deptIdArray);
                    for (Users users1 : usersPara) {
                        userIdReq += users1.getUserId() + ",";
                    }
                }
                for (String userId : userIdList) {
                    if (userIdReq.contains(userId + ",")) {
                        okParaList.add(userId);
                    }
                }
            } else if (para == 3) {
                //只能查看自己和自己部门下的
                List<Users> usersList = usersMapper.getUsersByDeptId(users.getDeptId());
                for (Users users1 : usersList) {
                    userIdReq += users1.getUserId() + ",";
                }
                for (String userId : userIdList) {
                    if (userIdReq.contains(userId + ",")) {
                        okParaList.add(userId);
                    }
                }
            } else {
                okParaList = userIdList;
            }
            Map<String, Object> map = new HashMap<>();
            map.put("tiqianbanjie", tiqianbanjie);
            map.put("anshibanjie", anshibanjie);
            map.put("chaoshibanjie", chaoshibanjie);
            map.put("anshibanli", anshibanli);
            map.put("chaoshibanli", chaoshibanli);
            map.put("beginDate", beginDate);
            map.put("endDate", endDate);
            for (String userId : okParaList) {
                map.put("userId", userId);
                Map<String, Object> tongJiMap = flowAbilityMonitorMapper.getChangGuiTongJi(map);
                Users user = usersMapper.getUsersByuserId(userId);
                String deptName = departmentMapper.getDeptNameById(user.getDeptId());
                tongJiMap.put("userName", user.getUserName());
                tongJiMap.put("deptName", deptName);
                mapList.add(tongJiMap);
            }
        } else {
            //没有权限
        }
        if(export==1||export==2){
            exportExcel(export,mapList,response);
        }
         //导出
        if (mapList != null) {
            // baseWrapper.setTotal(pageParams.getTotal());
            baseWrapper.setMsg("ok");
            baseWrapper.setFlag(true);
            baseWrapper.setDatas(mapList);
        }
        return baseWrapper;
    }


    public static long time(Date workStart, Date workDeadline, List<Map<Object, Object>> list, List<FlowSettingHoliday> holidays) {
        long time = 0;

        if (workDeadline.getTime() >= workStart.getTime()) {
            FlowRunFuServiceImpl.time2(workStart, workDeadline, list, holidays);
        }
        return time;
    }

    public static String time2(Date workStart, Date workDeadline, List<Map<Object, Object>> list, List<FlowSettingHoliday> holidays) {

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String time2 = simpleDateFormat.format(workStart); //开始时间转为 年月日
        String time3 = simpleDateFormat.format(workDeadline);//办理时限转为 年月日
        long time4 = workStart.getTime();   //开始时间转为 时间戳
        long time5 = workDeadline.getTime();//办理时限转为 时间戳
        //节假日
        List<FlowSettingHoliday> holiday = holidays;
        if (holiday.size() > 0) {
            for (FlowSettingHoliday ho : holiday) {
                if (!StringUtils.checkNull(ho.getBeginDate()) && !StringUtils.checkNull(ho.getEndDate())) {
                    Map<Object, Object> map = new HashMap<>(); //存放节假日开始时间和结束时间
                    StringBuffer beginDate = new StringBuffer(ho.getBeginDate());
                    StringBuffer endDate = new StringBuffer(ho.getEndDate());
                    beginDate.append(" 00:00:01");
                    endDate.append(" 23:59:59");
                    map.put(beginDate, endDate);
                }
            }
            FlowRunFuServiceImpl.calWorkTime("2018-11-1 00:00:00", list);
            //考勤时间
            FlowRunFuServiceImpl.time3(list);
        }
        return time2;
    }

    /**
     * 考勤时间 计算
     *
     * @param list
     * @return
     */
    public static Long[] time3(List<Map<Object, Object>> list) {

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyy-MM-dd HH:mm:ss");
        long beginNum = 0;  //开始时间 时间戳
        long endNum = 0;//结束时间 时间戳
        Long[] times = null;
        try {
            if (list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    Map<Object, Object> map = list.get(i);
                    //取出Map 中  Key
                    Set<Object> set = map.keySet();
                    Iterator<Object> it = set.iterator();
                    int index = -1;
                    int count = 0;
                    //取出 Map中 Vaule
                    Collection<Object> collection = map.values();
                    //存放 开始时间
                    Long[] times2 = new Long[map.size() - 1];
                    //存放 结束时间
                    Long[] times3 = new Long[map.size() - 1];
                    //循环 Key
                    while (it.hasNext()) {
                        count++;
                        index++;
                        if (count == set.size()) {
                            break;
                        }
                        String time = it.next().toString();
                        Date date = simpleDateFormat.parse("2018-10-30 " + time);
                        beginNum = date.getTime();
                        times2[index] = Long.valueOf(beginNum);
                    }
                    int index2 = -1;
                    int count2 = 0;
                    //循环 Vaules
                    for (Object obj : collection) {
                        index2++;
                        count2++;
                        if (count2 == collection.size()) {
                            break;
                        }
                        String time2 = obj.toString();
                        Date date2 = simpleDateFormat.parse("2018-10-30 " + time2);
                        endNum = date2.getTime();
                        times3[index2] = Long.valueOf(endNum);
                    }
                    //计算 开始时间和结束时间 差
                    for (int j = 0; j < times2.length; j++) {
                        long time4 = times3[j] - times2[j];
                        times = new Long[j + 1];
                        times[j] = Long.valueOf(time4);
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return times;
    }

    /**
     * 公共计算时间
     *
     * @param time 时间
     * @param list 考勤集合
     * @return
     */
    public static long calWorkTime(Object time, List<Map<Object, Object>> list) {

        long time2 = 0;
        SimpleDateFormat simpleDate = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        StringBuffer str = new StringBuffer();
        Object time3;
        long beginNum = 0;  //开始时间 时间戳
        long endNum = 0;//结束时间 时间戳
        try {
            //不是时间戳转为时间戳
            if (time instanceof java.lang.Long) {
                time3 = time;
            } else {
            }
            //获取当前时间的 年 月 日
            Calendar calendar = Calendar.getInstance();
            int year = calendar.get(Calendar.YEAR);
            int month = calendar.get(Calendar.MONTH) + 1;
            int day = calendar.get(Calendar.DAY_OF_MONTH);
            str.append(year + "-").append(month + "-").append(day + " ");
            //截取时分秒
            String time4 = time.toString().substring(time.toString().indexOf(" ") + 1);
            Long stNum = null;
            //有时分秒 当前日期拼上时分秒转时间戳
            if (!StringUtils.checkNull(time4)) {
                str.append(time4);
                Date ss = simpleDate.parse(str.toString());
                stNum = ss.getTime() / 1000;
            } else {
                //没有时分秒当前日期拼上00:00:00转时间戳   当山峰没有棱角的时候
                str.append("00:00:00");
                Date st = simpleDate.parse(str.toString());
                stNum = st.getTime() / 1000;
            }

            if (list.size() > 0) {

            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return time2;
    }

    public BaseWrappers queryFlowRunZhongList(Integer page, Integer pageSize, boolean useFlag, HttpServletResponse response, HttpServletRequest request, Integer runId, String runName, String state, String beginDate, String endDate, String status, String userId) {

        BaseWrappers baseWrapper = queryFlowRunZhong2(page, pageSize, useFlag, response, request, runId, runName, state, beginDate, endDate, status, userId);
        return baseWrapper;
    }


    /**
     * 重点工作监察  lr
     *
     * @param page
     * @param pageSize
     * @param useFlag
     * @param response
     * @param request
     * @param runId
     * @param runName
     * @param state
     * @param beginDate
     * @param endDate
     * @param statusType
     * @return
     */
    public BaseWrappers queryFlowRunZhong2(Integer page, Integer pageSize, boolean useFlag, HttpServletResponse response,
                                           HttpServletRequest request, Integer runId, String runName, String state,
                                           String beginDate, String endDate, String statusType, String userId) {

        BaseWrappers baseWrapper = new BaseWrappers();
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
        List<FlowPara> flowParaList = flowParaMapper.getFlowParaList();
        Map<String, String> flowParaMap = new HashMap();
        for (int i = 0; i < flowParaList.size(); i++) {
            FlowPara flowPara = flowParaList.get(i);
            flowParaMap.put(flowPara.getParaName(), flowPara.getParaValue());
        }
        String xiaolingdao = "DATA_36";
        String qiantoudanwei = "DATA_39";
        String flowIdF = flowParaMap.get("FLOW_ID_F");
        String flowIdS = flowParaMap.get("FLOW_ID_S");
        //当前用户权限
        Integer userPrar = get_user_right(user, flowParaMap);
        if (userPrar != 0) {
            Map<String, Object> map1 = new HashMap<>();
            //用户可查看的用户串
            String userIdreq = "";
            //最终查询List
            List<String> userIdList = new ArrayList<>();
            if (userPrar == 3) {
                userIdreq = isPara(userPrar, user);
                if (state != null && userId != null && !userId.equals("")) {
                    String[] userArrays = userId.split(",");
                    for (String userArray : userArrays) {
                        if (userIdreq.contains(userArray + ",")) {
                            userIdList.add(userArray);
                        }
                    }
                } else {
                    if (userIdreq != null && !userIdreq.equals("")) {
                        String[] userIdArray = userIdreq.split(",");
                        userIdList = new ArrayList<>(Arrays.asList(userIdArray));
                    }

                }
            } else if (userPrar == 2) {
                userIdreq = isPara(userPrar, user);
                if (state != null && userId != null && !userId.equals("")) {
                    String[] userArrays = userId.split(",");
                    for (String userArray : userArrays) {
                        if (userIdreq.contains(userArray + ",")) {
                            userIdList.add(userArray);
                        }
                    }
                } else {
                    if (userIdreq != null && !userIdreq.equals("")) {
                        String[] userIdArray = userIdreq.split(",");
                        userIdList = new ArrayList<>(Arrays.asList(userIdArray));
                    }
                }
            } else if (userPrar == 1) {
                if (state != null && userId != null && !userId.equals("")) {
                    String[] userArrays = userId.split(",");
                    for (String userArray : userArrays) {
                        userIdList.add(userArray);
                    }
                } else {
                    map1.put("para", userPrar);
                }
            }
            if (userIdList != null && userIdList.size() > 0) {
                map1.put("userIdList", userIdList);
            }
            map1.put("runId", runId);
            map1.put("workTitle", runName);
            map1.put("state", state);
            map1.put("beginTime", beginDate);
            map1.put("endTime", endDate);
            map1.put("statusType", statusType);
            PageParams pageParams = new PageParams();
            pageParams.setPage(page);
            pageParams.setPageSize(pageSize);
            pageParams.setUseFlag(useFlag);
            if (flowParaMap.size() > 0) {
                String[] impAdvance = flowParaMap.get("IMP_ADVANCE").split(",");
                String[] impRemind = flowParaMap.get("IMP_REMIND").split(",");
                if (impRemind[1].equals("h")) {
                    map1.put("impRemind0", Integer.parseInt(impRemind[0]) * 3600);
                } else if (impRemind[1].equals("%")) {
                    map1.put("impRemind0", Integer.parseInt(impRemind[0]) / 100);
                }
                if (impAdvance[1].equals("h")) {
                    map1.put("impAdvance0", Integer.parseInt(impAdvance[0]) * 3600);
                } else if (impRemind[1].equals("%")) {
                    map1.put("impAdvance0", Integer.parseInt(impAdvance[0]) / 100);
                }
                map1.put("impRemind1", impRemind[1]);
                map1.put("impAdvance1", impAdvance[1]);
            }
            List<FlowAbilityMonitor> flowAbilityMonitors = new ArrayList<>();
            Integer count = flowAbilityMonitorMapper.getFlowAbilityMonitorCountByMap(map1);
            map1.put("page", pageParams);
            List<Integer> runIdList = flowAbilityMonitorMapper.getFlowAbilityMonitorByMap(map1);
            if (runIdList != null) {
                for (int i = 0; i < runIdList.size(); i++) {
                    FlowAbilityMonitor flowAbilityMonitor = new FlowAbilityMonitor();
                    Integer runIdDb = runIdList.get(i);
                    Map map = new HashMap();
                    map.put("runId", runIdDb);
                    map.put("workType", 1);
                    map.put("userType", 1);
                    List<FlowAbilityMonitor> flowAbilityMonitorList = flowAbilityMonitorMapper.getFlowAbilityMonitorList(map);
                    if (flowAbilityMonitorList != null && flowAbilityMonitorList.size() > 0) {
                        flowAbilityMonitor = flowAbilityMonitorList.get(0);
                    } else {
                        map.put("runId", runIdDb);
                        map.put("workType", 1);
                        map.put("userType", 2);
                        map.put("oder", 1);
                        List<FlowAbilityMonitor> flowAbilityMonitorList2 = flowAbilityMonitorMapper.getFlowAbilityMonitorList(map);
                        if (flowAbilityMonitorList2 != null && flowAbilityMonitorList2.size() > 0) {
                            flowAbilityMonitor = flowAbilityMonitorList2.get(0);
                        }
                    }
                    //
                    if (flowAbilityMonitor != null) {
                        //查责任领导和牵头单位
                        Map<String, Object> dataMap = new HashMap();
                        dataMap.put("xiaolingdao", xiaolingdao);
                        dataMap.put("qiantoudanwei", qiantoudanwei);
                        dataMap.put("tableName", "flow_data_" + flowIdF);
                        dataMap.put("runId", flowAbilityMonitor.getRunId());
                        Map<String, String> mapData = flowAbilityMonitorMapper.getDataValue(dataMap);
                        if (mapData != null) {
                            //牵头单位
                            String danwei = mapData.get(qiantoudanwei);
                            if (danwei == null) {
                                danwei = mapData.get("data_39");
                            }
                            //负责校领导
                            String lingdao = mapData.get(xiaolingdao);
                            if (lingdao == null) {
                                lingdao = mapData.get("data_36");
                            }
                            if (danwei != null && !danwei.equals("")) {
                                // String[] danweis = danwei.split(",");
                                flowAbilityMonitor.setQiantou(danwei);
                            } else {
                                flowAbilityMonitor.setQiantou("");
                            }
                            if (lingdao != null && !lingdao.equals("")) {
                                //String[] lingdaos = lingdao.split(",");
                                flowAbilityMonitor.setZiren(lingdao);
                            } else {
                                flowAbilityMonitor.setZiren("");
                            }
                        }
                        flowAbilityMonitor.setFlowF(flowIdF);
                        flowAbilityMonitor.setFlowS(flowIdS);
                        //
                        //查用户名字
                        if (flowAbilityMonitor.getUserId() != null && !flowAbilityMonitor.getUserId().equals("")) {
                            String userName = usersMapper.getUsernameByUserId(flowAbilityMonitor.getUserId());
                            if (userName != null && !userName.equals("")) {
                                flowAbilityMonitor.setUserName(userName);
                            } else {
                                flowAbilityMonitor.setUserName("");
                            }
                        } else {
                            flowAbilityMonitor.setUserName("");
                        }
                        //查部门名字
                        if (flowAbilityMonitor.getDeptId() != null && !flowAbilityMonitor.getDeptId().equals("")) {
                            String deptName = departmentMapper.getDeptNameByDeptId(Integer.parseInt(flowAbilityMonitor.getDeptId()));
                            if (deptName != null && !deptName.equals("")) {
                                flowAbilityMonitor.setDeptName(deptName);
                            } else {
                                flowAbilityMonitor.setDeptName("");
                            }
                        } else {
                            flowAbilityMonitor.setDeptName("");
                        }
                        //时限计算（包括据办理时限）
                        flowAbilityMonitor = setShiXian(flowAbilityMonitor);
                        flowAbilityMonitors.add(flowAbilityMonitor);
                    }
                }
                if (flowAbilityMonitors.size() > 0) {
                    baseWrapper.setTotal(count);
                    baseWrapper.setDatas(flowAbilityMonitors);
                    baseWrapper.setFlag(true);
                    baseWrapper.setMsg("ok");
                    baseWrapper.setObject(userPrar);
                }
            } else {
                baseWrapper.setFlag(false);
                baseWrapper.setMsg("没有查询到数据");
            }
        } else {
            baseWrapper.setFlag(false);
            baseWrapper.setMsg("您没有查看权限");
        }
        return baseWrapper;
    }

    //统一权限控制
    public Integer get_user_right(Users user, Map<String, String> flowParaMap) {
        Integer userPrar = 0;
        if (flowParaMap.size() > 0 && user != null) {
            String userId = user.getUserId() + ",";
            if (flowParaMap.get("FLOW_LIULAN_ID").contains(userId)) {
                userPrar = 3;
            } else if (flowParaMap.get("FLOW_JUBU_ID").contains(userId)) {
                userPrar = 2;
            } else if (flowParaMap.get("FLOW_QUANMIAN_ID").contains(userId)) {
                userPrar = 1;
            }
        }
        return userPrar;
    }

    public FlowAbilityMonitor setShiXian(FlowAbilityMonitor flowAbilityMonitor) {
        //获取办理时限
        String workDeadline = flowAbilityMonitor.getWorkDeadline();
        String endDate = flowAbilityMonitor.getWorkEnd();//结束时间
        if (workDeadline != null && !workDeadline.equals("") && !workDeadline.equals("2000-01-01 00:00:00")) {
            String startDate = flowAbilityMonitor.getWorkStart();//开始时间
            String userId = flowAbilityMonitor.getUserId();
            Integer workDeadlineNum = DateFormat.getTime(workDeadline);
            //获取开始办理时限
            Integer startNum = DateFormat.getTime(startDate);
            Integer time = workDeadlineNum - startNum;

            if (time >= 0) {
                flowAbilityMonitor.setShixian(DateFormat.returnTime(time));
            } else {
                flowAbilityMonitor.setShixian("");
            }
            //如果未办结
            if (endDate == null || endDate.equals("") || endDate.equals("2000-01-01 00:00:00")) {
                //Integer workTimes = getUserDutyByUserId(userId, sdf.format(new Date()), workDeadline);
                long dqTime = new Date().getTime() / 1000;
                Integer workTimes = (int) (workDeadlineNum - dqTime);
                String shijian = DateFormat.returnTime(Math.abs(workTimes));
                if (workTimes >= 0) {//剩余
                    flowAbilityMonitor.setShijian("剩余" + shijian);
                } else if (workTimes < 0) {//超出
                    flowAbilityMonitor.setShijian("超出" + shijian);
                }
                //如果当前时间大于截止时间，则为超时办理
                if (dqTime > workDeadlineNum) {
                    //超时办理中
                    flowAbilityMonitor.setWorkStatusInt(2);
                } else {
                    //正常办理中
                    flowAbilityMonitor.setWorkStatusInt(1);
                }

            } else {
                //Integer workTimes = getUserDutyByUserId(userId, endDate, workDeadline);
                Integer endTime = DateFormat.getTime(endDate);
                Integer workTimes = workDeadlineNum - endTime;
                String shijian = DateFormat.returnTime(Math.abs(workTimes));
                if (workTimes >= 0) {//剩余
                    flowAbilityMonitor.setShijian("剩余" + shijian);
                } else if (workTimes < 0) {//超出
                    flowAbilityMonitor.setShijian("超出" + shijian);
                }

                if (endTime > workDeadlineNum) {
                    //超时办结
                    flowAbilityMonitor.setWorkStatusInt(4);
                } else {
                    //正常办结
                    flowAbilityMonitor.setWorkStatusInt(3);
                }

            }
        } else {
            if (endDate == null || endDate.equals("") || endDate.equals("2000-01-01 00:00:00")) {
                flowAbilityMonitor.setWorkStatusInt(5);
            } else {
                flowAbilityMonitor.setWorkStatusInt(6);
            }
            flowAbilityMonitor.setShixian("无时限");
            flowAbilityMonitor.setShijian("无时限");
        }
        return flowAbilityMonitor;
    }

    /**
     * 获取当前用户排班情况
     */
    public Integer getUserDutyByUserId(String userId, String beginDate, String endDate) {
        Integer uid = flowAbilityMonitorMapper.getUidByUserId(userId);
        Integer workTimes = 0;
        String beginTime = beginDate.split(" ")[0];
        String endTime = endDate.split(" ")[0];
        String beginTime2 = beginDate.split(" ")[1];
        String endTime2 = endDate.split(" ")[1];
        if (uid != null) {
            List<UserDuty> userDutyList = userDutyMapper.getUserDutyListByUidAndDates(uid, beginTime, endTime);
            if (userDutyList != null && userDutyList.size() > 0) {
                Set<Integer> set = new HashSet<>();
                //去重，得到用到的考勤id
                for (int i = 0; i < userDutyList.size(); i++) {
                    set.add(userDutyList.get(i).getDutyType());
                }
                if (set.size() > 0) {
                    List<Integer> sids = new ArrayList<>(set);
                    //防止循环查数据库，根据sid全查出来
                    List<AttendSet> attendSetList = flowAbilityMonitorMapper.getAttendSetByIds(sids);
                    if (attendSetList != null && attendSetList.size() > 0) {
                        Map<Integer, AttendSet> attendSetMap = new HashMap<>();
                        for (int j = 0; j < attendSetList.size(); j++) {
                            //装配map
                            attendSetMap.put(attendSetList.get(j).getSid(), attendSetList.get(j));
                        }
                        if (attendSetMap.size() > 0) {
                            for (int a = 0; a < userDutyList.size(); a++) {
                                UserDuty userDuty = userDutyList.get(a);
                                Integer sid = userDuty.getDutyType();
                                AttendSet attendSet = attendSetMap.get(sid);
                                if (attendSet != null) {
                                    Map<String, Object> map = getAttendSetCount(attendSet);
                                    if (map != null) {
                                        Integer workTime = Integer.parseInt(map.get("workTime").toString());
                                        AttendSet attendSet1 = (AttendSet) map.get("attendSet");
                                        if (beginTime.equals(endTime)) {//代表同一天
                                            workTimes = getShengYuTime(beginTime2, endTime2, attendSet1, 3);
                                            break;
                                        }
                                        if (userDuty.getDutyDate().equals(beginTime)) {
                                            workTimes = workTimes + getShengYuTime(beginTime2, endTime2, attendSet1, 1);
                                        } else if (userDuty.getDutyDate().equals(endTime)) {
                                            workTimes = workTimes + getShengYuTime(beginTime2, endTime2, attendSet1, 2);
                                        } else {
                                            workTimes = workTimes + workTime;
                                        }

                                    }
                                }
                            }
                        }
                    }
                }
            }

        }
        return workTimes;
    }

    /**
     * 将剩余时间加上
     *
     * @param beginTime
     * @param endTime
     * @param attendSet
     * @return
     */
    public Integer getShengYuTime(String beginTime, String endTime, AttendSet attendSet, Integer type) {
        Integer workTime = 0;
        Integer beginNum = DateFormat.getWYQTime(beginTime);
        Integer endNum = DateFormat.getWYQTime(endTime);
        Integer flag = null;
        Map<Integer, Integer> map = new HashMap<>();
        if (!attendSet.getAtime1Setother().equals("0") && !attendSet.getAtime2Setother().equals("0")) {
            if (attendSet.getAtime1() != null && attendSet.getAtime2() != null) {
                Integer time1 = DateFormat.getWYQTime(attendSet.getAtime1());
                Integer time2 = DateFormat.getWYQTime(attendSet.getAtime2());
                flag = 1;
                if (type == 1) {
                    if (beginNum >= time1 && beginNum < time2) {
                        flag = 1;
                        map.put(1, time2 - beginNum);
                    } else {
                        map.put(1, time2 - time1);
                    }
                } else if (type == 2) {
                    if (endNum > time1 && endNum <= time2) {
                        flag = 1;
                        map.put(1, endNum - time1);
                    } else {
                        map.put(1, time2 - time1);
                    }
                }
                if (type == 3) {
                    //增加计算同一天两时间中间的时间戳
                    if (beginNum >= time1 && beginNum < time2) {//如果开始时间在第一开关区间中
                        if (endNum >= time1 && endNum <= time2) {//如果结束时间也在此区间，返回中间毫秒值
                            map.put(1, endNum - beginNum);
                        } else {
                            map.put(1, time2 - beginNum);
                        }
                    } else if (beginNum < time1) {
                        if (endNum >= time1 && endNum <= time2) {
                            map.put(1, endNum - time1);
                        } else if (endNum > time2) {
                            map.put(1, time2 - time1);
                        }
                    }
                }
            }
        }
        if (!attendSet.getAtime3Setother().equals("0") && !attendSet.getAtime4Setother().equals("0")) {
            if (attendSet.getAtime3() != null && attendSet.getAtime4() != null) {
                Integer time1 = DateFormat.getWYQTime(attendSet.getAtime3());
                Integer time2 = DateFormat.getWYQTime(attendSet.getAtime4());
                flag = 2;
                if (type == 1) {
                    if (beginNum >= time1 && beginNum < time2) {
                        flag = 2;
                        map.put(2, time2 - beginNum);
                    } else {
                        map.put(2, time2 - time1);
                    }
                } else if (type == 2) {
                    if (endNum > time1 && endNum <= time2) {
                        flag = 2;
                        map.put(2, endNum - time1);
                    } else {
                        map.put(2, time2 - time1);
                    }
                }
                if (type == 3) {
                    //增加计算同一天两时间中间的时间戳
                    if (beginNum >= time1 && beginNum < time2) {//如果开始时间在第二开关区间中
                        if (endNum >= time1 && endNum <= time2) {//如果结束时间也在此区间，返回中间毫秒值
                            map.put(2, endNum - beginNum);
                        } else {
                            map.put(2, time2 - beginNum);
                        }
                    } else if (beginNum < time1) {//开始时间<time1
                        if (endNum >= time1 && endNum <= time2) {
                            map.put(2, endNum - time1);
                        } else if (endNum > time2) {
                            map.put(2, time2 - time1);
                        }
                    }
                }
            }
        }
        if (!attendSet.getAtime5Setother().equals("0") && !attendSet.getAtime6Setother().equals("0")) {
            if (attendSet.getAtime5() != null && attendSet.getAtime6() != null) {
                Integer time1 = DateFormat.getWYQTime(attendSet.getAtime5());
                Integer time2 = DateFormat.getWYQTime(attendSet.getAtime6());
                flag = 3;
                if (type == 1) {
                    if (beginNum >= time1 && beginNum < time2) {
                        flag = 3;
                        map.put(3, time2 - beginNum);
                    } else {
                        map.put(3, time2 - time1);
                    }
                } else if (type == 2) {
                    if (endNum > time1 && endNum <= time2) {
                        flag = 3;
                        map.put(3, endNum - time1);
                    } else {
                        map.put(3, time2 - time1);
                    }
                }
                if (type == 3) {
                    //增加计算同一天两时间中间的时间戳
                    if (beginNum >= time1 && beginNum < time2) {//如果开始时间在第三开关区间中
                        if (endNum >= time1 && endNum <= time2) {//如果结束时间也在此区间，返回中间毫秒值
                            map.put(2, endNum - beginNum);
                        } else {
                            map.put(2, time2 - beginNum);
                        }
                    } else if (beginNum < time1) {//开始时间<time1
                        if (endNum >= time1 && endNum <= time2) {
                            map.put(2, endNum - time1);
                        } else if (endNum > time2) {
                            map.put(2, time2 - time1);
                        }
                    }
                }
            }
        }
        if (flag != null) {
            if (type == 1) {
                switch (flag) {
                    case 1:
                        Integer num1 = map.get(1);
                        if (map.get(2) != null) {
                            num1 = num1 + map.get(2);
                        }
                        if (map.get(3) != null) {
                            num1 = num1 + map.get(3);
                        }
                        workTime = num1;
                        break;
                    case 2:
                        Integer num2 = map.get(2);
                        if (map.get(3) != null) {
                            num2 = num2 + map.get(3);
                        }
                        workTime = num2;
                        break;
                    case 3:
                        Integer num3 = map.get(3);
                        workTime = num3;
                        break;
                }
            } else {
                switch (flag) {
                    case 1:
                        Integer num1 = map.get(1);
                        break;
                    case 2:
                        Integer num2 = map.get(2);
                        if (map.get(1) != null) {
                            num2 = num2 + map.get(1);
                        }
                        workTime = num2;
                        break;
                    case 3:
                        Integer num3 = map.get(3);
                        if (map.get(2) != null) {
                            num3 = num3 + map.get(2);
                        }
                        if (map.get(1) != null) {
                            num3 = num3 + map.get(3);
                        }
                        workTime = num3;
                        break;
                }
            }

        }

        return workTime / 1000;
    }


    /**
     * 计算当前考勤一天总时长(时间戳)
     *
     * @param attendSet
     * @return
     */
    public Map<String, Object> getAttendSetCount(AttendSet attendSet) {
        try {
            Class c = attendSet.getClass().forName("com.xoa.model.attend.AttendSet");
            c.newInstance();
            for (int i = 1; i <= 6; i++) {
                Method methodget = c.getMethod("getAtime" + i + "Set");
                String getAtimeSet = (String) methodget.invoke(attendSet);
                if (getAtimeSet != null) {
                    if (getAtimeSet.contains("|")) {
                        String[] getAtimeSets = getAtimeSet.split("\\|");
                        String kaiguan = getAtimeSets[0];
                        Method methodset = c.getMethod("setAtime" + i + "Setother", new Class[]{String.class});
                        methodset.invoke(attendSet, new Object[]{kaiguan});
                    }
                }
            }
            Integer workTime = 0;
            if (!attendSet.getAtime1Setother().equals("0") && !attendSet.getAtime2Setother().equals("0")) {
                if (attendSet.getAtime1() != null && attendSet.getAtime2() != null) {
                    Integer time1 = DateFormat.getWYQTime(attendSet.getAtime1());
                    Integer time2 = DateFormat.getWYQTime(attendSet.getAtime2());
                    Integer time = time2 - time1;
                    workTime = workTime + time;
                }
            }
            if (!attendSet.getAtime3Setother().equals("0") && !attendSet.getAtime4Setother().equals("0")) {
                if (attendSet.getAtime3() != null && attendSet.getAtime4() != null) {
                    Integer time1 = DateFormat.getWYQTime(attendSet.getAtime3());
                    Integer time2 = DateFormat.getWYQTime(attendSet.getAtime4());
                    Integer time = time2 - time1;
                    workTime = workTime + time;
                }
            }
            if (!attendSet.getAtime5Setother().equals("0") && !attendSet.getAtime6Setother().equals("0")) {
                if (attendSet.getAtime5() != null && attendSet.getAtime6() != null) {
                    Integer time1 = DateFormat.getWYQTime(attendSet.getAtime5());
                    Integer time2 = DateFormat.getWYQTime(attendSet.getAtime6());
                    Integer time = time2 - time1;
                    workTime = workTime + time;
                }
            }
            Map<String, Object> map = new HashMap<>();
            map.put("workTime", workTime / 1000);
            map.put("attendSet", attendSet);
            return map;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @创建作者:李然 Lr
     * @方法描述：获取当前重点流程的子流程
     * @创建时间：15:58 2019/2/12
     **/
    @Override
    public BaseWrappers queryFlowRunZhongList(Integer parentRunId) {
        BaseWrappers baseWrapper = new BaseWrappers();
        List<FlowPara> flowParaList = flowParaMapper.getFlowParaList();
        Map<String, String> flowParaMap = new HashMap();
        List<FlowAbilityMonitor> flowAbilityMonitorList = new ArrayList<>();
        for (int i = 0; i < flowParaList.size(); i++) {
            FlowPara flowPara = flowParaList.get(i);
            flowParaMap.put(flowPara.getParaName(), flowPara.getParaValue());
        }
        String fuzeren = "DATA_9";
        String flowIdF = flowParaMap.get("FLOW_ID_F");
        String flowIdS = flowParaMap.get("FLOW_ID_S");
        List<FlowAbilityMonitor> flowAbilityMonitors = flowAbilityMonitorMapper.getWorkSonByParentId(parentRunId);
        if (flowAbilityMonitors != null && flowAbilityMonitors.size() > 0) {
            for (int i = 0; i < flowAbilityMonitors.size(); i++) {
                FlowAbilityMonitor flowAbilityMonitor = flowAbilityMonitors.get(i);
                if (flowAbilityMonitor != null) {
                    flowAbilityMonitor.setFlowF(flowIdF);
                    flowAbilityMonitor.setFlowS(flowIdS);
                    //查责任领导和牵头单位
                    Map<String, Object> dataMap = new HashMap();
                    dataMap.put("qiantoudanwei", fuzeren);
                    dataMap.put("tableName", "flow_data_" + flowIdS);
                    dataMap.put("runId", flowAbilityMonitor.getRunId());
                    Map<String, String> mapData = flowAbilityMonitorMapper.getDataValue(dataMap);
                    if (mapData != null) {
                        //负责人
                        String fuze = mapData.get(fuzeren);
                        if (fuze == null) {
                            fuze = mapData.get("data_9");
                        }
                        if (fuze != null && !fuze.equals("")) {
                            // String[] danweis = danwei.split(",");
                            flowAbilityMonitor.setZiren(fuze);
                        } else {
                            flowAbilityMonitor.setZiren("");
                        }

                    }
                    //
                    //查用户名字
                    if (flowAbilityMonitor.getUserId() != null && !flowAbilityMonitor.getUserId().equals("")) {
                        String userName = usersMapper.getUsernameByUserId(flowAbilityMonitor.getUserId());
                        if (userName != null && !userName.equals("")) {
                            flowAbilityMonitor.setUserName(userName);
                        } else {
                            flowAbilityMonitor.setUserName("");
                        }
                    } else {
                        flowAbilityMonitor.setUserName("");
                    }
                    //查部门名字
                    /*if (flowAbilityMonitor.getDeptId() != null && !flowAbilityMonitor.getDeptId().equals("")) {
                        String deptName = departmentMapper.getDeptNameByDeptId(Integer.parseInt(flowAbilityMonitor.getDeptId()));
                        if (deptName != null && !deptName.equals("")) {
                            flowAbilityMonitor.setDeptName(deptName);
                        } else {
                            flowAbilityMonitor.setDeptName("");
                        }
                    } else {
                        flowAbilityMonitor.setDeptName("");
                    }*/
                    //时限计算（包括据办理时限）
                    flowAbilityMonitor = setShiXian(flowAbilityMonitor);
                    flowAbilityMonitorList.add(flowAbilityMonitor);
                }
            }
            if (flowAbilityMonitorList.size() > 0) {
                baseWrapper.setDatas(flowAbilityMonitorList);
                baseWrapper.setFlag(true);
                baseWrapper.setMsg("ok");
            }
        } else {
            //没有数据
        }
        return baseWrapper;
    }

    /**
     * 查询重点流程类型
     */
    @Override
    public ToJson<FlowTypeModel> selectImportantFlowType() {
        ToJson<FlowTypeModel> json = new ToJson<>(0, "ok");
        //List<FlowTypeModel> flowTypes = flowTypeModelMapper.selectImportantFlowTypes();
        //json.setObj(flowTypes);
        //json.setTotleNum(flowTypes.size());
        return json;
    }

    /**
     * 查出当前流程的父流程与子流程
     *
     * @param flowId
     * @param runId
     * @return
     */
    public ToJson parentAndSon(Integer flowId, Integer runId) {
        ToJson toJson = new ToJson();
        //父流程
        Map<String, Integer> parentRun = flowAbilityMonitorMapper.getParentRunByRunId(runId.toString());
        //子流程
        List<FlowRun> sonFlowRun = flowAbilityMonitorMapper.getSonFlowRun(runId.toString(), null);
        toJson.setFlag(0);
        toJson.setObj(sonFlowRun);
        toJson.setObject(parentRun);
        return toJson;
    }

    //定时任务
    //@Scheduled(cron = "*/1 * * * * ?")
   /* public synchronized void job1() {
        synchronized (this){
            threadPoolTaskExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    //查询
                }
            });
        }
        System.out.println("---=====>>>> " + " 定时任务正在执行...");
    }*/


   //重点工作统计和常规工作统计通用导出
   public void exportExcel(Integer exType,List<Map<String, Object>> mapList,HttpServletResponse response){
       if(mapList!=null&&mapList.size()>0){

           try {
               int rowNum=2;//行数计数器

               // 获取当前时间
               Calendar c = Calendar.getInstance();
               String time =  ""+c.get(Calendar.YEAR) + (c.get(Calendar.MONTH) + 1)
                       + c.get(Calendar.DAY_OF_MONTH) + c.get(Calendar.HOUR_OF_DAY)
                       + c.get(Calendar.MINUTE);
               StringBuffer stringBuffer = new StringBuffer();
               HSSFWorkbook wb = new HSSFWorkbook();
               // 第二步，在webbook中添加一个sheet,对应Excel文件中的sheet
               HSSFSheet sheet = wb.createSheet("效能监察统计");

               // 第四步，创建单元格，并设置值表头 设置表头居中
               HSSFFont font = wb.createFont();
               font.setFontHeightInPoints((short) 11); // 字体高度
               font.setColor(HSSFFont.COLOR_NORMAL); // 字体颜色
               font.setFontName("宋体"); // 字体
               font.setBold(true);// 宽度
               font.setItalic(false); // 是否使用斜体
               HSSFCellStyle style = wb.createCellStyle();
               style.setAlignment(HorizontalAlignment.CENTER); // 创建一个居中格式
               style.setVerticalAlignment(VerticalAlignment.CENTER);
               style.setFont(font);
               style.setBorderBottom(BorderStyle.THIN); //下边框
               style.setBorderLeft(BorderStyle.THIN);//左边框
               style.setBorderTop(BorderStyle.THIN);//上边框
               style.setBorderRight(BorderStyle.THIN);//右边框
               HSSFFont font1 = wb.createFont();
               font1.setFontHeightInPoints((short) 11); // 字体高度
               font1.setColor(HSSFFont.COLOR_NORMAL); // 字体颜色
               font1.setFontName("宋体"); // 字体
               font1.setBold(true); // 宽度
               font1.setItalic(false); // 是否使用斜体
               HSSFCellStyle style1 = wb.createCellStyle();
               style1.setVerticalAlignment(VerticalAlignment.CENTER);
               style1.setAlignment(HorizontalAlignment.CENTER); // 创建一个居中格式
               style1.setFont(font1);
               style1.setWrapText(true);
               style1.setBorderBottom(BorderStyle.THIN); //下边框
               style1.setBorderLeft(BorderStyle.THIN);//左边框
               style1.setBorderTop(BorderStyle.THIN);//上边框
               style1.setBorderRight(BorderStyle.THIN);//右边框
               HSSFFont font0 = wb.createFont();
               font0.setFontName("方正小标宋简体");//设置字体名称
               font0.setFontHeightInPoints((short)20);//设置字号
               font0.setColor(HSSFFont.COLOR_NORMAL);//设置字体颜色
               font0.setUnderline(HSSFFontFormatting.U_SINGLE);//设置下划线
               HSSFCellStyle style0 = wb.createCellStyle();
               style0.setVerticalAlignment(VerticalAlignment.CENTER);
               style0.setAlignment(HorizontalAlignment.CENTER); // 创建一个居中格式
               style0.setFont(font0);
               // 设置每一列的宽度
               //sheet.setDefaultColumnWidth(30);

               sheet.setDefaultRowHeight((short)(300*2));
               //sheet.setColumnWidth(0, 256*12); //设置某一列宽度
               sheet.setColumnWidth(0, 256*15); //设置某一列宽度
               sheet.setColumnWidth(1, 256*15); //设置某一列宽度
               sheet.setColumnWidth(2, 256*15); //设置某一列宽度
               sheet.setColumnWidth(3, 256*15); //设置某一列宽度
               sheet.setColumnWidth(4, 256*15); //设置某一列宽度
               sheet.setColumnWidth(5, 256*15); //设置某一列宽度
               sheet.setColumnWidth(6, 256*15); //设置某一列宽度
               sheet.setColumnWidth(7, 256*15); //设置某一列宽度
               String oneTitle=null;
               if(exType==1){
                   oneTitle="重点工作统计";
               }else if(exType==2){
                   oneTitle="常规工作统计";
               }
               HSSFRow oneRow =sheet.createRow(0);
               HSSFCell Cell=oneRow.createCell(0);
               Cell.setCellValue(oneTitle);
               Cell.setCellStyle(style0);
               String [] titleArray={"用户","所在部门","参与工作数量","提前办结（%）","按时办结（%）","超时办结（%）","按时办理中（%）","超时办理中（%）"};
               CellRangeAddress regionRow0 = new CellRangeAddress(0, 0, 0, titleArray.length-1);
               sheet.addMergedRegion(regionRow0);
               HSSFRow row =sheet.createRow(1);
               for(int j=0;j<titleArray.length;j++){
                   HSSFCell hssfCell=row.createCell(j);
                   hssfCell.setCellValue(titleArray[j]);
                   hssfCell.setCellStyle(style);
               }
               for(Map<String,Object> map:mapList){
                   String userName=String.valueOf(map.get("userName"));
                   String deptName=String.valueOf(map.get("deptName"));
                   String count=String.valueOf(map.get("count"));
                   String tiqianban=String.valueOf(map.get(tiqianbanjie));
                   String anshibanj=String.valueOf(map.get(anshibanjie));
                   String chaoshibanj=String.valueOf(map.get(chaoshibanjie));
                   String anshibanl=String.valueOf(map.get(anshibanli));
                   String chaoshibanl=String.valueOf(map.get(chaoshibanli));
                   List<String> cellStrList=new ArrayList<>();
                   cellStrList.add(userName);
                   cellStrList.add(deptName);
                   cellStrList.add(nullTo0(count));
                   cellStrList.add(nullTo0(tiqianban));
                   cellStrList.add(nullTo0(anshibanj));
                   cellStrList.add(nullTo0(chaoshibanj));
                   cellStrList.add(nullTo0(anshibanl));
                   cellStrList.add(nullTo0(chaoshibanl));
                   HSSFRow row1 =sheet.createRow(rowNum);//创建一行
                   for(int i=0;i<cellStrList.size();i++){
                        HSSFCell hssfCell=row1.createCell(i);
                        hssfCell.setCellValue(cellStrList.get(i));
                        hssfCell.setCellStyle(style1);
                   }
                   rowNum++;

               }

               stringBuffer.append("效能监察统计").append(time.toString()).append(".xls");
               String fileName = stringBuffer.toString();
               response.setHeader("Content-disposition", "attachment;filename="
                       + URLEncoder.encode(fileName, "UTF-8"));
               response.setContentType("application/msexcel;charset=UTF-8");
               OutputStream out = response.getOutputStream();
               wb.write(out);
               out.close();
           } catch (IOException e) {
               e.printStackTrace();
           }

       }


   }
    public String nullTo0(String str){
       if(str==null||str.trim().equals("")){
           str="0";
       }
       return str;
    }

}
